const { delTask, getUserTaskPage } = require('../../../utils/task');
const { formatDateTime, formatDateTimeNoSeconds } = require('../../../utils/date');
Page({
  data: {
    tasks: [],
    current: 1,
    size: 10,
    hasMore: true,
    loading: false,
    showImageViewer: false,
    previewImageUrl: '',
    stateList: [
      {
        label: '待执行',
        value: 'wait_run'
      },
      {
        label: '运行中',
        value: 'running'
      },
      {
        label: '已结束',
        value: 'finish'
      },
      {
        label: '已取消',
        value: 'cancel'
      },
      
    ],
    needRefresh: false,
    ripple: {
      show: false,
      x: 0,
      y: 0
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadTasks(true);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查是否需要刷新数据
    if (this.data.needRefresh) {
      this.setData({ needRefresh: false });
      this.loadTasks(true);
    }
  },

  async loadTasks(reset) {
    if (this.data.loading || (!this.data.hasMore && !reset)) return;
    this.setData({ loading: true });
    const current = reset ? 1 : this.data.current;
    try {
      const res = await getUserTaskPage(current, this.data.size);
      const newTasks = res.records || [];
      const tasks = reset ? newTasks : this.data.tasks.concat(newTasks);
      // 对任务开始和结束时间进行格式化
      tasks.forEach(task => {
        task.taskStartTimeFmt = formatDateTime(task.taskStartTime);
        task.taskEndTimeFmt = formatDateTime(task.taskEndTime);
        task.joinTime = formatDateTimeNoSeconds(task.joinTime);
        task.stateFmt = this.data.stateList.find(item => item.value === task.state) ?.label || '未知';
        task.stateClass = task.state;
      });
      this.setData({
        tasks,
        current: current + 1,
        hasMore: tasks.length < (res.total || 0),
        loading: false
      });
    } catch (e) {
      this.setData({ loading: false });
      wx.showToast({ title: '加载任务失败', icon: 'none' });
    }
  },

  onScrollToLower() {
    this.loadTasks(false);
  },

  onEditTask(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/task/manage-task/manage-task?taskId=${id}` });
  },

  onDeleteTask(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '删除任务',
      content: '该操作非可逆行为，请谨慎操作',
      confirmText: '删除',
      confirmColor: '#ff3b30',
      success: (res) => {
        if (res.confirm) {
          delTask(id).then(() => {
            wx.showToast({ title: '删除成功', icon: 'success' });
            this.loadTasks(true);
          }).catch((e) => {
            wx.showToast({ title: e.data.msg || '删除失败', icon: 'none' });
          });
        }
      }
    });
  },

  onDetailTask(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/task/task-detail/task-detail?id=${id}` });
  },

  onCheckInTask(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/task/check-in-detail/check-in-detail?id=${id}` });
  },

  onPublishTask(e) {
    const taskId = e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.taskid;
    let url = '/pages/task/manage-task/manage-task';
    if (taskId) url += `?taskId=${taskId}`;
    wx.navigateTo({ url });
  },

  onPreviewImage(e) {
    const url = e.currentTarget.dataset.url;
    this.setData({
      showImageViewer: true,
      previewImageUrl: url
    });
  },

  onImageViewerClose() {
    this.setData({
      showImageViewer: false,
      previewImageUrl: ''
    });
  },
  onRipple(e) {
    // 获取点击位置（相对于按钮左上角）
    const touch = e.touches[0];
    const query = this.createSelectorQuery();
    query.select('.publish-task-btn').boundingClientRect(rect => {
      if (rect) {
        const x = touch.clientX - rect.left - 50; // 50为半径
        const y = touch.clientY - rect.top - 50;
        this.setData({
          ripple: {
            show: true,
            x,
            y
          }
        });
        setTimeout(() => {
          this.setData({
            'ripple.show': false
          });
        }, 400); // 动画时长
      }
    }).exec();
  },
})